import {setToken, removeToken} from '@/util/auth'
import {setStore, getStore} from '@/util/store'
import {isURL, validatenull} from '@/util/validate'
import {deepClone} from '@/util/util'
import webiste from '@/config/website'
import {querySysMenuTreeByUserId, querySysButtonByUserId} from '@/api/system/sysMenuApi';
import {querySysMenuTopListPage} from '@/api/system/sysMenuTopApi';
import {loginByUsername,refreshToken,logOut} from '@/api/system/sysUserInfoApi';
import store from '@/store/';
import console from '@/util/console'

function addPath(ele, first) {
  const menu = webiste.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  };
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  if (!isChild) ele[propsDefault.children] = [];
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach(child => {
      addPath(child);
    })
  }
}

const user = {
  state: {
    userInfo: getStore({name: 'userInfo'}) || [],
    permission: getStore({name: (getStore({name: 'userInfo'})? getStore({name: 'userInfo'}).userId : '')+'permission'}) || {},
    roles: [],
    menu: getStore({name: (getStore({name: 'userInfo'})? getStore({name: 'userInfo'}).userId : '')+'menu1'}) || [],
    token: localStorage.getItem('TOKEN') || '',
    refreshToken: getStore({name: 'refreshToken'}) || '',
    projectInfo: getStore({ name: (getStore({name: 'userInfo'})? getStore({name: 'userInfo'}).userId : '')+'projectInfo'}) || {},
    accessId: localStorage.getItem('accessId') || ''
  },
  actions: {
    //设置用户信息
    setUserInfo: ({ commit }, v) => commit('SET_USERIFNO', v),
    //设置菜单
    setMenu: ({ commit }, v) => commit('SET_MENU', v),
    // 设置项目信息
    setProjectInfo: ({ commit }, v) => commit('SET_PROJECT_INFO', v),

    //根据用户名登录
    LoginByUsername({commit}, commonData) {
      console.log('==LoginByUsername==');
      return new Promise((resolve, reject) => {
        loginByUsername(commonData).then(res => {
          const data = res.data;
          commit('SET_TOKEN', data.value);
          commit('SET_REFRESH_TOKEN', data.refreshToken.value);
          data.additionalInformation.userInfo.expiresIn = data.expiresIn;
          commit('SET_USERIFNO', data.additionalInformation.userInfo);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          resolve(data);
        }).catch(error => {
          reject(error);
        })
      })
    },

    //刷新token
    RefreshToken({commit}, commonData) {
      console.log('==RefreshToken==');
      return new Promise((resolve, reject) => {
        refreshToken(commonData).then(res => {
          const data = res.data;
          //console.log('======res',data)
          commit('SET_TOKEN', data.value);
          commit('SET_REFRESH_TOKEN', data.refreshToken.value);
          data.additionalInformation.userInfo.expiresIn = data.expiresIn;
          commit('SET_USERIFNO', data.additionalInformation.userInfo);
          resolve(data);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({commit, state}) {
      console.log('==LogOut==');
      commit('SET_PROJECT_INFO', '');
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_ROLES', [])
      commit('DEL_ALL_TAG');
      commit('CLEAR_LOCK');
      commit('CLEAR_MENU');
      commit('SET_USERIFNO', '');
      localStorage.removeItem('TOKEN');
      localStorage.removeItem('accessId');
      removeToken();
    },
    //注销session
    FedLogOut({commit}) {
      console.log('==FedLogOut==');
      return new Promise(resolve => {
        commit('SET_PROJECT_INFO', '');
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        commit('CLEAR_MENU');
        commit('SET_USERIFNO', '');
        localStorage.removeItem('TOKEN');
        localStorage.removeItem('accessId');
        localStorage.setremoveItemItem('xId');
        localStorage.removeItem('xUserName');
        localStorage.removeItem('xToken');
        removeToken()
        resolve()
      })
    },
    GetTopMenu({state},commonData) {
      return new Promise(resolve => {
        let topMenu = getStore({name: 'topMenu'+state.userInfo.userId})
        if(commonData.recordChanged.isTopMenuChanged || !topMenu || topMenu.length == 0){
          querySysMenuTopListPage(commonData.commonArea).then((res) => {
            const data = res.data.body.listBody || []
            setStore({name: state.userInfo.userId+'topMenu', content: data, type: ''})
            //console.log('getTopMenu = ',data)
            resolve(data)
          })
        }
        else {
          let topMenu =  getStore({name: state.userInfo.userId+'topMenu'});
          resolve(topMenu)
        }
      })
    },
    //获取系统菜单
    GetMenu({state,commit, dispatch}, commonData) {
      return new Promise(resolve => {
        //console.log('== tate.menu= ',commonData.level)
        // 如果发生了改变或者本地存储为空时从远程获取
        let projectMenu = getStore({name: state.userInfo.userId+'projectMenu'+store.getters.projectInfo.id+commonData.level})
        let menus = getStore({name: state.userInfo.userId+'menu'+commonData.level})
        if(commonData.recordChanged.isMenuChanged || !menus || menus.length == 0){
          querySysMenuTreeByUserId(commonData.commonArea).then((res) => {
            const data = res.data.body.listBody
            let menu = deepClone(data);
            menu.forEach(ele => {
              addPath(ele, true);
            })
            setStore({name: state.userInfo.userId+'menu'+commonData.level, content: menu, type: ''})
            // dispatch('GetButtons',commonData);
            if(projectMenu){
              commit('SET_MENU', menu.concat(projectMenu));
              resolve(menu.concat(projectMenu));
              //console.log('====projectMenu === ',menu.concat(projectMenu))
            }
            else {
              commit('SET_MENU', menu);
              resolve(menu);
            }
          })
        }
        else {
          let menu =  getStore({name: state.userInfo.userId+'menu'+commonData.level});
          if(projectMenu){
            commit('SET_MENU', menu.concat(projectMenu));
            resolve(menu.concat(projectMenu));
          }
          else {
            commit('SET_MENU', menu);
            resolve(menu);
          }
        }
      })
    },
    // 获取按钮
    GetButtons({state,commit},commonData) {
      let permission = getStore({name: state.userInfo.userId+'permission'});
      return new Promise((resolve) => {
        if(commonData.recordChanged.isMenuChanged || !permission){
          querySysButtonByUserId(commonData.commonArea).then(res => {
            const data = res.data.body.listBody[0];
            commit('SET_PERMISSION', data);
            resolve();
          })
        }
        else {
          let data = getStore({name: state.userInfo.userId+'permission'});
          commit('SET_PERMISSION', data);
          resolve();
        }
      })
    },
    //设置用户信息
  },
  mutations: {
    CLEAR_MENU: (state, token) => {
      setStore({name: state.userInfo.userId+'topMenu', content: '', type: ''})
      setStore({name: state.userInfo.userId+'menu1', content: '', type: ''})
      setStore({name: state.userInfo.userId+'menu2', content: '', type: ''})
      setStore({name: state.userInfo.userId+'menu3', content: '', type: ''})
      setStore({name: state.userInfo.userId+'menu4', content: '', type: ''})
      setStore({name: state.userInfo.userId+'menu5', content: '', type: ''})
      setStore({name: state.userInfo.userId+'permission', content: '', type: ''})
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
      localStorage.setItem('TOKEN',token);
      localStorage.setItem('xToken',token);
      localStorage.setItem('accessId',new Date().getTime());
      setToken(token)
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken;
      setStore({name: 'refreshToken', content: state.refreshToken, type: 'session'})
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
      localStorage.setItem('xId',userInfo.userId);
      localStorage.setItem('xUserName',userInfo.userName);
      setStore({name: 'userInfo', content: state.userInfo})
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission  = permission;
      setStore({name: state.userInfo.userId+'permission', content: state.permission, type: ''})
    },
    SET_PROJECT_INFO: (state, projectInfo) => {
      state.projectInfo = projectInfo;
      setStore({ name: state.userInfo.userId+'projectInfo', content: projectInfo, type: 'session' })
    }
  }

}
export default user
